package com.nebula.service.Impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.common.collect.Maps;
import com.nebula.common.Const;
import com.nebula.common.ServerResponse;
import com.nebula.mapper.FoldersMapper;
import com.nebula.mapper.UserGroupsMapper;
import com.nebula.mapper.UserMapper;
import com.nebula.pojo.Folders;
import com.nebula.pojo.User;
import com.nebula.service.IUserService;
import com.nebula.util.FileUtil;
import com.nebula.util.MD5Util;
import com.nebula.vo.NicknameVo;

import oracle.net.aso.f;

@Service("userService")
public class UserServiceImpl implements IUserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserGroupsMapper userGroupsMapper;
	@Autowired
	private FoldersMapper foldersMapper;
	
	public ServerResponse<User> login(String username,String password){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int resultCount = userMapper.checkLoginUsername(username);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("账号不存在");
		}
		String md5Password = MD5Util.MD5EncodeUtf8(password);
		resultCount = userMapper.login(username, md5Password);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("账号或密码错误，请重新输入！");
		}
		String loginName = userMapper.selectUsernameByLoginName(username);
		User user = userMapper.selectUserInfo(loginName);
		if(user.getNickname() == null){user.setNickname(StringUtils.EMPTY);}
		if(user.getRealname() == null){user.setRealname(StringUtils.EMPTY);}
		if(user.getPhone() == null){user.setPhone(StringUtils.EMPTY);}
		if(user.getSex() == null){user.setSex("男");}
		if(user.getBirthday() == null){
			try {
				user.setBirthday(sdf.parse("1990-01-01"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return ServerResponse.createBySuccess("登录成功",user);
	}
	
	public ServerResponse<User> endecodLogin(String username,String password){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int resultCount = userMapper.checkLoginUsername(username);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("账号不存在");
		}
		resultCount = userMapper.login(username, password);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("账号或密码错误，请重新输入！");
		}
		String loginName = userMapper.selectUsernameByLoginName(username);
		User user = userMapper.selectUserInfo(loginName);
		if(user.getNickname() == null){user.setNickname(StringUtils.EMPTY);}
		if(user.getRealname() == null){user.setRealname(StringUtils.EMPTY);}
		if(user.getPhone() == null){user.setPhone(StringUtils.EMPTY);}
		if(user.getSex() == null){user.setSex("男");}
		if(user.getBirthday() == null){
			try {
				user.setBirthday(sdf.parse("1990-01-01"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return ServerResponse.createBySuccess("登录成功",user);
	}
	
	public ServerResponse<String> register(User user){
		ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
		if(!validResponse.isSuccess()){
			return validResponse;
		}
		validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
		if(!validResponse.isSuccess()){
			return validResponse;
		}
		int groupId = userGroupsMapper.selectByGroupName(Const.CUSTOMER);
		user.setGroupid(groupId);
		user.setIsdataperfect(0);
		user.setUsedStorageSpace(0l);
		
		//MD5加密
		user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
		int resultCount = userMapper.insert(user);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("注册失败");
		}
		Folders folders = new Folders();
		folders.setFolderName("我的文件");
		folders.setInRecycle(1);
		folders.setParentid(0);
		folders.setUsername(user.getUsername());
		resultCount = foldersMapper.insert(folders);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("注册失败");
		}
		int folderId = foldersMapper.selectAllFileFolderIdByUsername(user.getUsername());
		folders.setFolderName("我的资源");
		folders.setInRecycle(1);
		folders.setParentid(folderId);
		folders.setUsername(user.getUsername());
		resultCount = foldersMapper.insert(folders);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("注册失败");
		}
		return ServerResponse.createBySuccessMessage("注册成功");
	}
	
	public ServerResponse<String> checkValid(String str,String type){
		if(StringUtils.isNotBlank(type)){
			if(Const.EMAIL.equals(type)){
				int resultCount = userMapper.checkEmail(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("邮箱已存在");
				}
			}
			if(Const.USERNAME.equals(type)){
				int resultCount = userMapper.checkUsername(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("用户名已存在");
				}
			}
		}else {
			return ServerResponse.createByErrorMessage("参数错误");
		}
		return ServerResponse.createBySuccess();
	}
	
	public ServerResponse checkPassword(String username,String password){
		int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(password), username);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("旧密码正确");
		}
		return ServerResponse.createByErrorMessage("旧密码错误");
	}
	
	public ServerResponse usedSize(String username){
		User user = userMapper.selectUserInfo(username);
		Map<String, Object> map = Maps.newHashMap();
		map.put("usedSize", user.getUsedStorageSpace());
		map.put("maxSize", user.getUserGroups().getMaxStorageSpace());
		map.put("USEDSIZE",FileUtil.byteCountToDisplaySize(user.getUsedStorageSpace()));
		map.put("MAXSIZE",FileUtil.unreservedDecimalPoint(user.getUserGroups().getMaxStorageSpace()));
		return ServerResponse.createBySuccess("查询成功",map);
	}
	
	public ServerResponse<NicknameVo> userInfo(String username){
		User user = userMapper.selectByPrimaryKey(username);
		NicknameVo nicknameVo = new NicknameVo();
		if(user.getNickname() == null){
			nicknameVo.setNickname("-");
		}else{
			nicknameVo.setNickname(user.getNickname());
		}
		
		nicknameVo.setUsername(username);
		
		return ServerResponse.createBySuccess(nicknameVo);
	}
	
	public ServerResponse<String> setNickname(String username,String nickname){
		User user = new User();
		user.setUsername(username);
		user.setNickname(nickname);
		int resultCount = userMapper.updateByPrimaryKeySelective(user);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("设置昵称成功");
		}
		return ServerResponse.createByErrorMessage("设置昵称失败");
	}
	
	public ServerResponse updateUserGroupId(String username,Integer groupId){
		User user = new User();
		user.setUsername(username);
		user.setGroupid(groupId);
		int resultCount = userMapper.updateByPrimaryKeySelective(user);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("更新用户GroupId信息成功");
		}
		return ServerResponse.createByErrorMessage("更新用户GroupId信息成功");
	}
	
	public ServerResponse checkNickname(String nickname){
		int resultCount = userMapper.checkNickname(nickname);
		if(resultCount > 0){
			return ServerResponse.createByErrorMessage("昵称已存在");
		}
		return ServerResponse.createBySuccessMessage("昵称可用");
	}
	
	public ServerResponse change_password(String username,String password){
		User user = new User();
		user.setUsername(username);
		user.setPassword(MD5Util.MD5EncodeUtf8(password));
		int resultCount = userMapper.updateByPrimaryKeySelective(user);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("修改密码成功");
		}
		return ServerResponse.createByErrorMessage("修改密码错误");
	}
	
	public ServerResponse checkInformation(String str,String username,String type){
		if("email".equals(type)){
			User user = userMapper.selectByEmail(str);
			if(user == null){
				return ServerResponse.createBySuccess();
			}else{
				if(username.equals(user.getUsername())){
					return ServerResponse.createBySuccess();
				}
			}
		}else if("phone".equals(type)){
			User user = userMapper.selectByPhone(str);
			if(user == null){
				return ServerResponse.createBySuccess();
			}else{
				if(username.equals(user.getUsername())){
					return ServerResponse.createBySuccess();
				}
			}
		}else if("nickname".equals(type)){
			User user = userMapper.selectByNickname(str);
			if(user == null){
				return ServerResponse.createBySuccess();
			}else{
				if(username.equals(user.getUsername())){
					return ServerResponse.createBySuccess();
				}
			}
		}
		return ServerResponse.createByError();
	}
	
	public ServerResponse updateInformation(User user){
		int resultCount = userMapper.updateByPrimaryKeySelective(user);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("修改个人资料成功");
		}
		return ServerResponse.createByErrorMessage("修改个人资料失败");
	}
}
